package cn.iocoder.yudao.module.erp.service.stock.bom;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.stock.bom.vo.BomPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.stock.bom.vo.BomSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.bom.BomDO;
import cn.iocoder.yudao.module.erp.dal.mysql.stock.bom.BomMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.BOM_NOT_EXISTS;

/**
 * BOM Service 实现类
 *
 * @author maxuxu
 */
@Service
@Validated
public class BomServiceImpl implements BomService {

    @Resource
    private BomMapper bomMapper;

    @Override
    public Long createBom(BomSaveReqVO createReqVO) {
        // 插入
        BomDO bom = BeanUtils.toBean(createReqVO, BomDO.class);
        bomMapper.insert(bom);
        // 返回
        return bom.getId();
    }

    @Override
    public void updateBom(BomSaveReqVO updateReqVO) {
        // 校验存在
        validateBomExists(updateReqVO.getId());
        // 更新
        BomDO updateObj = BeanUtils.toBean(updateReqVO, BomDO.class);
        bomMapper.updateById(updateObj);
    }

    @Override
    public void deleteBom(Long id) {
        // 校验存在
        validateBomExists(id);
        // 删除
        bomMapper.deleteById(id);
    }

    private void validateBomExists(Long id) {
        if (bomMapper.selectById(id) == null) {
            throw exception(BOM_NOT_EXISTS);
        }
    }

    @Override
    public BomDO getBom(Long id) {
        return bomMapper.selectById(id);
    }

    @Override
    public PageResult<BomDO> getBomPage(BomPageReqVO pageReqVO) {
        return bomMapper.selectPage(pageReqVO);
    }

    @Override
    public void deleteAnyBOM(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
         bomMapper.deleteBatchIds(ids);
    }

}